//
//  UITextView+Extension.swift
//  01-keyBoard
//
//  Created by Leon on 15/10/25.
//  Copyright © 2015年 Leon. All rights reserved.
//

import UIKit

// MARK: - UITextView图文并写扩展方法
extension UITextView {
    
    /// 返回完整的表情字符串
    var emoticonText: String {
        
        var strM = String()
        
        let attString = attributedText
        attString.enumerateAttributesInRange(NSRange(location: 0, length: attString.length), options: []) { (dict, range, _) -> Void in
            
            if let attachment = dict["NSAttachment"] as? EmoticonTextAttachment {
                strM += attachment.chs ?? ""
            } else {
                strM += (attString.string as NSString).substringWithRange(range)
            }
        }
        
        return strM
    }
    
    ///  在文本中插入表情
    ///
    ///  - parameter em: 表情模型
    func insertEmoticon(em: EmoticonModel) {
        
        // 1 空白按钮
        if em.isEmpty {
            return
        }
        
        // 2 如果是删除按钮
        if em.isRemoved {
            deleteBackward()
            return
        }
        
        // 3 如果是 emoji 表情
        if let emoji = em.code {
            replaceRange(selectedTextRange!, withText: emoji)
            return
        }
        
        // 4 如果是 图片表情
        insertImageText(em)
        
        // 5. 通知`代理`文本变化了 － textViewDidChange? 表示代理如果没有实现方法，就什么都不做，更安全
        delegate?.textViewDidChange?(self)

    }
    
    private func insertImageText(em: EmoticonModel) {
        
        // 1> 取出图片附件
        let imageText = EmoticonTextAttachment.imageText(em, font: font!)
        
        // 2> 获取textView的属性文本
        let textM = NSMutableAttributedString(attributedString: attributedText)
        
        textM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        
        // 3> 记录光标位置
        let cursorLocation = selectedRange.location + 1
        
        attributedText = textM
        
        selectedRange = NSRange(location: cursorLocation, length: 0)
    }
}
